// 代码中会兼容本地 service mock 以及部署站点的静态数据
import { generate as generateId } from 'shortid';
import authorityInfo from './user_json/authorityInfo.json';

function commentFunc(req, res) {
  const commentRes = checkToken(req) || {
    code: '000000',
    message: '成功',
    data: {},
  };
  res.json(commentRes);
}
function commentFuncAarr(req, res) {
  const commentRes = checkToken(req) || {
    code: '000000',
    message: '成功',
    data: [],
  };
  res.json(commentRes);
}
function commentFuncSet(req, res, data) {
  const commentRes = checkToken(req) || {
    code: '000000',
    message: '成功',
    data,
  };
  res.json(commentRes);
}
function checkToken(req) {
  const { authorization: accessToken } = req.headers;
  const session = sessionInfo[accessToken];
  console.log(`url:${req.url}`);
  console.log(`accessToken:${accessToken}`);
  console.log(`session:${JSON.stringify(session)}`);
  if (!accessToken || accessToken === 'undefined' || !session) {
    return {
      code: 403,
      message: '非法请求',
    };
  }
  if (session.overdue) {
    return {
      code: 'AM4002',
      message: 'token过期',
    };
  }
  return false;
}

const userInfo = {
  admin: {
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    id: 1,
    username: 'admin',
    nikeName: '管理员',
    currentAuthority: 'admin',
    status: 1,
    timestamp: 1577325197854,
    phoneNumber: '18321548966',
  },
  user: {
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    id: 2,
    uname: 'user',
    nikeName: '用户',
    currentAuthority: 'user',
    status: 1,
    phoneNumber: '15521548966',
    timestamp: 1577325197854,
  },
};
const sessionInfo = {};
const tokenInfo = {};
const currentAuthorityMap = {
  user: [],
  admin: [
    'smsPush:view',
    'consultType:limit:page',
    'keyWordManager:view',
    'o2ostore:view',
    'risk:view',
    'o2obrandall:view',
    'userLogoutManage:view',
    'cityBusinessSecurity:view',
    'securityAccount:view',
    'user:delete:button',
    'personas:user',
    'tradeProduct:view',
    'logManager:view',
    'securityAccount:addButton',
    'thirdInsProduct:read:page',
    'appPush:manager',
    'inboxmsg:pushed',
    'admin:index',
    'o2orecommended:view',
    'epaymgmt:view',
    'advinfo:view',
    'joyContentVote:view',
    'real_channel:view',
    'smsManager:whiteList',
    'userManager:view',
    'businessLines:view',
    'userRegStatistics:view',
    'icon:config',
    'super',
    'iamSecuryTargetC:view',
    'deviceActivation:openZipView:page',
    'intelligent:view',
    'channel_spot:view',
    'usermgmt:view',
    'department:delete:button',
    'deviceInfoall:view',
    'userProfile:view',
    'fundAccount:search:button',
    'documentReview:pass:page',
    'role:delete:button',
    'thirdOrg:view',
    'inboxmsg:manager',
    'channel:view',
    'joyInsurePayLinkErrorLog:view',
    'refundAudit:button',
    'deviceinfoup:view',
    'privilege:view',
    'user:save:interface',
    'contentmgmt:view',
    'lableManager:view',
    'cityMinWage:view',
    'o2oproductall:view',
    'buzzConfig:view',
    'appFieldConfig:view',
    'billDifferenManage:view',
    'businessCount:view',
    'bankFee:view',
    'billDifferenManage:button',
    'analysisBugCollect:view',
    'insureCourseDailySummary:view',
    'mgmt:view',
    'insuranceProduct:view',
    'channelread:add:button',
    'joyIpUserMenu:view',
    'channelConfig:view',
    'securityAccount:search:button',
    'channelreadbuzz:del:button',
    'appLog:userLog',
    'smsPush:manager',
    'userTags:view',
    'couponMan:normalIn:button',
    'cityManager:view',
    'promotionChannel:delete:button',
    'filterConfig:sort:button',
    'wesuremgmt:view',
    'admUser:view',
    'role:view',
    'fundAccount:updateButton',
    'noticekeywordManager:view',
    'videoClipsMenu:view',
    'iamSecuryTargetA:view',
    'msgmgmt:view',
    'SecurityFundFaillog:view',
    'identity:view',
    'creditCardBank:delete:page',
    'product:view',
    'o2olink:view',
    'refundAudit:view',
    'socialSecurity:read:page',
    'userRegStatisticsTest:view',
    'specialAuthorityManager:view',
    'nounsExplanation:view',
    'order:view',
    'article:export:button',
    'promotionLinks:view',
    'ipUser:view',
    'feedback:view',
    'flowsManagner:view',
    'promotion:view',
    'promotionChannel:read:page',
    'datadict:view',
    'thirdInsProduct:view',
    'insureCourseReceive:view',
    'creditCardProduct:view',
    'specialColumn:view',
    'channel:close:button',
    'userManager:showUserDeatilInfo',
    'joyShareConfig:view',
    'score:view',
    'article:delete:button',
    'payConsultation:view',
    'specialAuthorityStatistics:view',
    'o2o:ins:button',
    'consultType:view',
    'o2oIns:view',
    'o2obrand:view',
    'pay:view',
    'article:view',
    'securityAccount:showDetail',
    'fee:view',
    'couponMan:high:button',
    'creditCardProduct:delete:page',
    'role:read:page',
    'videoType:view',
    'fundAccountTest:view',
    'securityProduct:view',
    'o2odoctorall:view',
    'department:read:page',
    'role:assign:page',
    'user:password:button',
    'cityPayment:read:page',
    'unemployedCalculator:view',
    'hongbao:view',
    'iconManager:view',
    'userLogout:view',
    'consultant:consultantManagement',
    'couponMan:view',
    'itemTags:view',
    'article:publish:button',
    'insureCourseCourse:view',
    'userInfoBrowseStatistics:view',
    'channelStatistics:view',
    'withholding:view',
    'riskConfig:view',
    'SecuritySuccessFaillog:view',
    'inboxmsg:view',
    'promotionLinks:delete:button',
    'cityMaintenance:view',
    'adL:view',
    'systemManagement:view',
    'consultConfig:view',
    'socialsecurity:view',
    'securityAccountTest:view',
    'real:view',
    'report:view',
    'thirdCominsOrg:view',
    'boundCardFail:view',
    'couponMan:normalO2O:button',
    'checkLogin:manager',
    'cityBusinessReport:view',
    'feedback:showDetail',
    'msgTypeManager:view',
    'paymentOrder:view',
    'o2oo2orefundall:view',
    'insureCourseQuizzes:view',
    'fundAccount:view',
    'businessOrder:view',
    'adv:view',
    'lableProfile:view',
    'maternityAllowance:view',
    'loanProductBase:view',
    'filterConfig:read:page',
    'thirdInsProduct:delete:button',
    'promotionChannel:view',
    'workOrder:view',
    'securityPersonnel:view',
    'user:view',
    'user:resetPassword:button',
    'userFirst:view',
    'lableManager:sortView',
    'user:read:page',
    'o2omgmt:view',
    'filterConfig:delete:button',
    'deviceinfo:view',
    'buzzAppoint:view',
    'article:withEntrance:button',
    'user:assign:page',
    'calculator:view',
    'o2orefund:view',
    'promotinoChannel:showPromotionChannelInfo',
    'userManagerTest:view',
    'extension:view',
    'couponMan:normal:button',
    'promotionLinks:showPromotionLinksDeatilInfo',
    'realmgmt:index',
    'creditCardProduct:read:page',
    'o2oSecurityManager:view',
    'naviGation:view',
    'inhabitantCalculator:view',
    'cityPayment:view',
    'cardInformation:view',
    'cityPayment:delete:button',
    'contentJoyShareConfigMenu:view',
    'user:update:button',
    'minfo:view',
    'creditCardBank:view',
    'activites:view',
    'userIp:view',
    'persoans:itemTags',
    'selfPush:view',
    'o2opredetermineall:view',
    'deviceActivation:view',
    'o2ondustryCategory:view',
    'user:create:button',
    'channelview:add:button',
    'o2ostoreRecommended:view',
    'insureCourseMenu:view',
    'creditCardBank:read:page',
    'channel:open:button',
    'thirdInsProductPV:view',
    'consultantUrl:consultantUrlManagement',
    'fundAccount:addButton',
    'o2ostoreall:view',
    'flexibleCalculator:view',
    'insureCourseColumn:view',
    'privilege:read:page',
    'fundAccount:showDetail',
    'operate:view',
    'Securitypassword:view',
    'cityBuzzRela:view',
    'consultQuestion:replyView',
    'channel:edit:button',
    'appLog:view',
    'channelread:save:button',
    'queryLogSearch:view',
    'cityBusiness:view',
    'cityBusinessfund:view',
    'documentReview:view',
    'coupon:config',
    'topic:view',
    'contentVoteMenu:view',
    'tieCardFaillog',
    'o2odoctor:view',
    'predetermineUser:view',
    'consultQuestion:view',
    'couponOV:view',
    'couponUser:view',
    'businessOrder:showDeatil',
    'securityService:view',
    'indexExtendConfig:view',
    'insuranceType:view',
    'topicMenu:view',
    'navigation:offLine:button',
    'insureCourseStatistics:view',
    'credit:view',
    'joyInsurePayLink:view',
    'smsLog:view',
    'promotionLinks:read:page',
    'article:browse:page',
    'o2oproduct:view',
    'minfoList:view',
    'article:read:page',
    'couponMan:normalSi:button',
    'intelligentMedical:view',
    'department:view',
    'o2olinkall:view',
    'userRegister:view',
    'calculationModular:view',
    'user:password:page',
    'o2o:ins:common:button',
    'channelRoute:view',
    'channelread:savever:button',
    'tieCardFaillog:bindingbutton',
    'cityOverview:view',
    'iamSecuryTargetB:view',
    'cityManager:showRadixInfo',
    'o2ocase:view',
    'userTags:search',
    'productMan:view',
    'securityAccount:updateButton',
    'privilege:delete:button',
    'subProduct:view',
    'o2opredetermine:view',
    'videoclips:view',
    'billFileExport:button',
    'itemKeyword:view',
    'o2o:ins:button',
    'o2oIns:view',
    'consultant:consultantManagement',
    'o2omgmt:view',
    'consultantUrl:consultantUrlManagement',
    'o2oIns:view',
    'o2omgmt:view',
    'o2o:ins:common:button',
    'epaymgmt:view',
    'icon:config',
    'refundAudit:button',
    'appFieldConfig:view',
    'billDifferenManage:view',
    'billDifferenManage:button',
    'channelConfig:view',
    'refundAudit:view',
    'pay:view',
    'article:view',
    'article:publish:button',
    'paymentOrder:view',
    'article:withEntrance:button',
    'extension:view',
    'minfo:view',
    'operate:view',
    'minfoList:view',
  ],
};

export default {
  // GET POST 可省略
  'POST /admin/api/login': (req, res) => {
    const { password, username } = req.body;
    if (String(password) === 'abc123' && username === 'admin') {
      const accessToken = generateId(32);
      const refreshToken = generateId(32);
      tokenInfo[refreshToken] = accessToken;
      sessionInfo[accessToken] = { ...userInfo.admin };
      console.log('write session:', accessToken);
      res.send({
        code: '000000',
        message: '操作成功',
        data: {
          userId: userInfo.admin.id,
          username: userInfo.admin.name,
          accessToken,
          refreshToken,
        },
      });
      return;
    }

    if (String(password) === '123456' && username === 'user') {
      const accessToken = generateId(32);
      const refreshToken = generateId(32);
      sessionInfo[accessToken] = userInfo.user;
      res.send({
        code: '000000',
        message: '操作成功',
        data: {
          userId: userInfo.admin.id,
          username: userInfo.admin.name,
          accessToken,
          refreshToken,
        },
      });
      return;
    }

    res.send({
      code: 'AM3000',
      message: '账号或密码错误',
    });
  },
  // 刷新token
  'POST /admin/api/refreshToken': (req, res) => {
    const { refreshToken: orefreshToken } = req.body;
    console.log(`refreshToken:${orefreshToken}`);
    const oaccessToken = tokenInfo[orefreshToken];
    if (oaccessToken) {
      const accessToken = generateId(32);
      const refreshToken = generateId(32);
      tokenInfo[refreshToken] = accessToken;
      sessionInfo[accessToken] = { ...sessionInfo[oaccessToken], overdue: false };
      delete tokenInfo[orefreshToken];
      delete sessionInfo[oaccessToken];
      res.json({
        code: '000000',
        message: '操作成功',
        data: {
          accessToken,
          refreshToken,
        },
      });
    } else {
      res.send({
        code: 'AM4001',
        message: 'token过期',
      });
    }
  },
  'GET /admin/api/overdueToken': (req, res) => {
    const { token } = req.query;
    const session = sessionInfo[token];
    console.log(`accessToken:${token}`);
    console.log(`session:${JSON.stringify(session)}`);
    session.overdue = true;
    res.json({
      code: '000000',
      message: '操作成功',
      data: session,
    });
  },

  // 查询当前用户信息 currentUser AM-024
  'GET /admin/api/AM-024': (req, res) => {
    const { authorization: accessToken } = req.headers;
    const session = sessionInfo[accessToken];
    commentFuncSet(req, res, session);
  },
  // 查询当前用户权限数组 queryUserPermissions AM-022
  'GET /admin/api/AM-022': (req, res) => {
    const { authorization: accessToken } = req.headers;
    const session = sessionInfo[accessToken];
    const authority = session ? currentAuthorityMap[session.username] : [];
    commentFuncSet(req, res, authority);
  },
  'GET /admin/api/AM-025': commentFuncAarr,
  'GET /admin/api/AM-026': commentFuncAarr,
  'POST /admin/api/AM-001': commentFuncAarr,
  // 支持值为 Object 和 Array
  'POST /admin/api/setPassword': commentFunc,
  // 支持值为 Object 和 Array
  'POST /admin/api/upUserInfo': commentFunc,

  'POST /admin/api/loginOut': (req, res) => {
    sessionInfo.loginInfo = false;
    res.end();
  },
};
